import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:test_for_pageview_lifecycle/video_urls.dart';
import 'package:video_player/video_player.dart';
import 'package:visibility_detector/visibility_detector.dart';

class PageGetWidgeItem extends GetWidget<PageItemController> {
  final int index;
  const PageGetWidgeItem({required this.index, super.key});

  @override
  Widget build(BuildContext context) {
    return VisibilityDetector(
      key: key!,
      onVisibilityChanged: (VisibilityInfo info) {
        if (info.visibleFraction == 1) {
          print('is visiable');
          controller.playVideo();
        }
        if (info.visibleFraction == 0) {
          controller.pauseVideo();
        }
      },
      child: Scaffold(
        floatingActionButton: FloatingActionButton(
          child: Icon(Icons.add),
          onPressed: () {
            print(controller.isVideoPlayerReady());
          },
        ),
        appBar: AppBar(title: Text('the NO.$index page')),
        body: GetBuilder<PageItemController>(
          // init: PageItemController(),
          initState: (_) =>
              controller.initializeVideoControllerWithIndex(index),
          builder: (_) {
            return Center(
                child: controller.isVideoPlayerReady()
                    ? AspectRatio(
                        aspectRatio: (16.0 / 9.0),
                        child: VideoPlayer(controller.videoPlayerController),
                      )
                    : const CircularProgressIndicator());
          },
        ),
      ),
    );
  }
}

class PageItemController extends GetxController {
  // final isCurrentVisiable = false.obs;
  late VideoPlayerController _videoPlayerController;
  // late int _index;

  // VideoPlayerController videoControler() {
  //   return _videoPlayerController;
  // }

  get videoPlayerController {
    return _videoPlayerController;
  }

  //action
  void initializeVideoControllerWithIndex(int index) {
    // _index = index;
    _videoPlayerController = VideoPlayerController.network(videoUrls[index])
      ..initialize();
  }

  bool isVideoPlayerReady() {
    return _videoPlayerController.value.isInitialized;
  }

  // set index(int newIndex) {
  //   _index = newIndex;
  // }

  void playVideo() {
    _videoPlayerController.play();
  }

  void pauseVideo() {
    _videoPlayerController.pause();
  }

  // void visiableChanged(bool isVisiable) {
  //   // isCurrentVisiable.value = isVisiable;
  //   isVisiable ? _videoPlayerController.play() : _videoPlayerController.pause();
  // }

  @override
  void onInit() {
    print('item controller init');
    // _videoPlayerController = VideoPlayerController.network(videoUrls[_index])
    //   ..initialize();
    super.onInit();
  }

  @override
  void onClose() {
    _videoPlayerController.dispose();
    super.onClose();
  }
}
